import axios, { AxiosInstance } from 'axios'
import { Message } from 'element-ui'
import qs from 'qs'

export class HttpServer {
  private instance!: AxiosInstance

  constructor() {
    this.instance = axios.create({
      timeout: 10000,
      baseURL: '/api',
    })
    this.init()
  }

  /** 初始化拦截器 */
  private init() {
    // 请求拦截器
    this.instance.interceptors.request.use(config => config, err => {
      Message.error('网络错误')
      throw new Error(err)
    })

    // 响应拦截器
    this.instance.interceptors.response.use(({ data }: any) => {
      const { code, msg } = data

      if (msg && msg !== '' && !data.data) {
        if (code === 200) {
          Message.success(msg)
        } else {
          Message.warning(msg)
        }
      }
      if (code !== 200) {
        throw new Error(msg)
      }
      return data.data
    }, err => {
      Message.error('网络错误')
      throw new Error(err)
    })
  }

  get(url: string, params?: any): Promise<any> {
    return new Promise((resolve, reject) => {
      this.instance.get(url, { params }).then(res => resolve(res))
        .catch(err => reject(err))
    })
  }

  post(url: string, params?: any): Promise<any> {
    return new Promise((resolve, reject) => {
      this.instance.post(url, qs.stringify(params)).then(res => resolve(res))
        .catch(err => reject(err))
    })
  }

  file(url: string, params?: any): Promise<any> {
    return new Promise((resolve, reject) => {
      this.instance.post(url, params, { headers: { 'Content-Type': 'multipart/form-data' } }).then(res => resolve(res))
        .catch(err => reject(err))
    })
  }

}

const Http = new HttpServer()

export default Http
